package com.book.service.impl;

import com.book.dao.BookMapper;
import com.book.entity.Book;
import com.book.service.BookService;
import com.book.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class BookServiceImpl implements BookService {
    @Override
    public List<Book> listBooks() {
        try (SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            return bookMapper.listBooks();
        }
    }

    @Override
    public Integer countBooks() {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            return bookMapper.countBooks();
        }
    }

    @Override
    public List<Book> listExistBooks() {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            return bookMapper.listExistBooks();
        }
    }

    @Override
    public Integer minusBookNumber(Integer id) {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            bookMapper.minusBookNumber(id);
            return 1;  // 成功执行返回1
        }
    }

    @Override
    public Integer getNumberById(Integer id) {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            return bookMapper.getNumberById(id);
        }
    }

    @Override
    public Integer insertBook(Book book) {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            bookMapper.insertBook(book);
        }
        return 1;
    }

    @Override
    public Book selectBookById(Integer id) {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            return bookMapper.selectBookById(id);
        }
    }

    @Override
    public void modifyBookNumber(Integer id, Integer number) {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            bookMapper.modifyBookNumber(id, number);
        }
    }

    @Override
    public void deleteById(Integer id) {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            bookMapper.deleteById(id);
        }
    }
}
